const baseURL = "https://obuge.com/juzao"

let interceptors = {//拦截器
  request(req){//请求拦截器
    return new Promise(next => {
      req.url = /^http/.test(req.url) ? req.url: (baseURL+req.url)
      next(req)
    })
  },
  response(res){//响应拦截器
    return new Promise(next =>{
      console.log(res)
      if(res.statusCode == 404){
        next({errorMsg:'请求接口不存在'})
      }else if(res.statusCode ==500){
        next({errorMsg:res.data ||'服务器错误，请联系管理员'})
      }else if(res.statusCode == 200) {//正常业务
        next(res.data)
      }else{
        next({errorMsg:res.errMsg ||'未知错误'})
      }
    })
  }
}


function GET(url,query){
    return new Promise((resolve,reject) =>{
      interceptors.request({url}).then(req =>{
        wx.request({
          ...req,
          data:query,
          success: (res) =>{
            interceptors.response(res).then(data =>{
              resolve(data)
            })
           },
           fail:(res) =>{
             interceptors.response(res).then(data =>{
              resolve(data)
            })
           }
        })
      })
    })
}

function PUT(url,data){
  return new Promise((resolve,reject) =>{
    interceptors.request({url}).then(req => {
      wx.request({
        ...req,
        data,
        method:'PUT',
        success: (res) =>{
          interceptors.response(res).then(data =>{
            resolve(data)
          })
         },
         fail:(res) =>{
           interceptors.response(res).then(data =>{
            resolve(data)
          })
         }
      })
    })
  })
}

function POST(url,data){
  return new Promise((resolve,reject) =>{
    interceptors.request({url}).then(req => {
      wx.request({
        ...req,
        data,
        method:'POST',
        success: (res) =>{
          interceptors.response(res).then(data =>{
            resolve(data)
          })
         },
         fail:(res) =>{
           interceptors.response(res).then(data =>{
            resolve(data)
          })
         }
      })
    })
  })
}

function DELETE(url,query){
  return new Promise((resolve,reject) =>{
    interceptors.request({url}).then(req => {
      wx.request({
        ...req,
        data:query,
        method:'delete',
        success: (res) =>{
          interceptors.response(res).then(data =>{
            resolve(data)
          })
         },
         fail:(res) =>{
           interceptors.response(res).then(data =>{
            resolve(data)
          })
         }
      })
    })
  })
}

module.exports = {
  baseURL,
  get:GET,
  put:PUT,
  post:POST,
  delete:DELETE
}
